<?php  

class LoginModul extends BasicModulController implements BasicModulControllerInterface {


    // -------- Login [origin] точка входа ----------
    function actionLoginBasic(){

        if(User::isAdmin()){
            header("Location:" . PUBLIC_URL);
        }

        if(isset($_SESSION[SESSION_SPACE]['auth']['messages'])){
           $this->view->messages = $_SESSION[SESSION_SPACE]['auth']['messages'];
        }

        $this->html = $this->view->fetch('Login.tpl');
        //$this->html = $this->view->render();

        //TODO отрисовать форму, ведущую на /login/auth




    } // --

    function actionLoginAuth(){
        $redirect = '/';

        /*
        if(isset($_SESSION['request_uri'])){
            if($_SESSION['request_uri'] != 'login'){
                $redirect .= $_SESSION['request_uri'];
            }
        }
        */


        if(Registry::getInstance()->session->has('request_uri')){
            $redirect = Registry::getInstance()->session->request_uri;
        }

        #
        $responcestatus = 'ok';

        #
        $login = Registry::getInstance() ->request->getParameter('login');
        $pass = Registry::getInstance() ->request->getParameter('pass');


        # валидация
        $validatorChain = new Zend\Validator\ValidatorChain();

        $validatorChain->addValidator(new Zend\Validator\NotEmpty() )
            ->addValidator(new Zend\Validator\StringLength(array('min' => 5, 'max' => 30)))
            ->addValidator( new PassValidator());

        if ($validatorChain->isValid($pass)) {
            // pass passed validation
            unset($_SESSION[SESSION_SPACE]['auth']['messages']);
        } else {
            // pass failed validation; print reasons
            unset( $_SESSION[SESSION_SPACE]['auth']['messages'] );

            foreach ($validatorChain->getMessages() as $message) {
                if(!isset( $_SESSION[SESSION_SPACE]['auth']['messages']))
                    $_SESSION[SESSION_SPACE]['auth']['messages'] = array();

                if(!in_array($message, $_SESSION[SESSION_SPACE]['auth']['messages']))
                     $_SESSION[SESSION_SPACE]['auth']['messages'][] = $message;
            }
            header("Location:" . PUBLIC_URL . "/" . 'login');
            die;
        }


        # doSecure(&$login)

        $user = User::isUserExists($login, $pass);

        # поиск в базе
        if( is_array($user) ){
            $User = new User($login = null, $pass = null, $user);
            $User->processUser();

        } else {

            $redirect = '';
            $responcestatus = 'failed';
        }



        #
        unset($_SESSION['request_uri']);
        
        if($redirect == '') header("Location:" . PUBLIC_URL .  $redirect);
        else        
          header("Location:" . PUBLIC_URL . "/" . $redirect);


    }





















    // -------- dining [virtual] точка входа ----------
    function actionDiningBasic(){

        $this->view->new_photo_form_action = PUBLIC_URL . '/'.$this->virtual_modul_index.'/ДобавитьФото/new';

        $this->view->unit = $unit = mb_strtolower($this->virtual_modul_index);

        Controller::appendHeadScript(PUBLIC_URL .'/js/jquery.fileupload.js');

        # TEST events
        $onCellSelect = "
            function (rowid, iCol, cellContent, e) {alert('23')
                        grid.restoreRow(lastSelection);
                        grid.editRow(rowid, true, null, null, null, null, null);
                        lastSelection = rowid;
                        }
        ";
        $loadCompleteAction = 'function(request)
       {
         jQuery("#photo_dining_grid").setCaption("gridcaption");
       }';

        # Grid
        $grid_unit = "photo_" . mb_strtolower($unit);
        $grid_name = $grid_unit . "_grid";
        $this->view->grid_unit = $grid_unit;
        $this->view->grid_name = $grid_name;

        $photo_grid = new GridWrapper($grid_unit);

        $options = array(
            'navigator' => true,
            'debug' => true,
            'url' => PUBLIC_URL . "/". mb_strtolower($this->view->unit)."/getphoto",
            'editurl' => PUBLIC_URL . "/$unit/editCell",
            'loadComplete' =>  new Zend\Json\Expr($loadCompleteAction),
            'navoptions' => array('edit', /*'search'*/),
        );

        $photo_grid->set_edit_options(array(
            'msg' => 'Error' ,
            'width' => 460
        ));

        $photo_grid->set($options);


        // test
       //$photo_grid->setGridParameter('loadComplete', new Zend\Json\Expr($loadCompleteAction));

        $photo_grid->_populate();

        // [!] Можно подключать так
        /*
        $code = "

             function multisave(e){

                        var grid_name = 'photo_dining_grid'
                        var url = 'http://admin.remontik.kh.ua/dining/multisave'
                        var data = 'save'

                        $.ajax({
                            type: 'POST',
                            url: url,
                            data: data,
                            success: function(dat){
                                jQuery('#' + grid_name).trigger('reloadGrid');
                                $('.multiload-box').html('');
                            },
                dataType: 'json'
                });

                }
        ";

        $code_dynamic = "

            $('button[name=valim_optom]').on('click',multisave);

        ";

        Controller::appendHeadCode($code);
        Controller::appendHeadCodeDynamic($code_dynamic);
        */

        $this->html = $this->view->fetch('basic.tpl');

        Controller::appendHeadScript(PUBLIC_URL . "/js/mebel.js");
    } // -- 

    // -------- chamber [virtual] точка входа ----------
    function actionChamberBasic(){
        $this->view->new_photo_form_action = PUBLIC_URL . '/'.$this->virtual_modul_index.'/ДобавитьФото/new';

        $this->view->unit = $unit = mb_strtolower($this->virtual_modul_index);

        Controller::appendHeadScript(PUBLIC_URL .'/js/jquery.fileupload.js');

        # Grid
        $grid_unit = "photo_" . mb_strtolower($unit);
        $grid_name = $grid_unit . "_grid";
        $this->view->grid_unit = $grid_unit;
        $this->view->grid_name = $grid_name;

        $photo_grid = new GridWrapper($grid_unit);

        $options = array(
            'navigator' => true,
            'debug' => true,
            'url' => PUBLIC_URL . "/". mb_strtolower($this->view->unit)."/getphoto",
            'editurl' => PUBLIC_URL . "/$unit/editCell",
            'navoptions' => array('edit'),
        );

        $photo_grid->set_edit_options(array(
            'msg' => 'Error' ,
            'width' => 460
        ));

        $photo_grid->set($options);

        $photo_grid->_populate();

        $this->html = $this->view->fetch('basic.tpl');

        Controller::appendHeadScript(PUBLIC_URL . "/js/mebel.js");
    } // --
    
    // -------- wardrobe [virtual] точка входа ----------
    function actionWardrobeBasic(){

        $this->view->new_photo_form_action = PUBLIC_URL . '/'.$this->virtual_modul_index.'/ДобавитьФото/new';

        $this->view->unit = $unit = mb_strtolower($this->virtual_modul_index);

        Controller::appendHeadScript(PUBLIC_URL .'/js/jquery.fileupload.js');

        # Grid
        $grid_unit = "photo_" . mb_strtolower($unit);
        $grid_name = $grid_unit . "_grid";
        $this->view->grid_unit = $grid_unit;
        $this->view->grid_name = $grid_name;

        $photo_grid = new GridWrapper($grid_unit);

        $options = array(
            'navigator' => true,
            'debug' => true,
            'url' => PUBLIC_URL . "/". mb_strtolower($this->view->unit)."/getphoto",
            'editurl' => PUBLIC_URL . "/$unit/editCell",
            'navoptions' => array('edit'),
        );

        $photo_grid->set_edit_options(array(
            'msg' => 'Error' ,
            'width' => 460
        ));

        $photo_grid->set($options);

        $photo_grid->_populate();

        $this->html = $this->view->fetch('basic.tpl');

        Controller::appendHeadScript(PUBLIC_URL . "/js/mebel.js");
    } // --

    function actionDiningGetphoto(){
        $this->setNoRender();

        $unit = mb_strtolower($this->registry->virtual_modul_index);
        $grid_unit = "photo_$unit";

        $data = $this->model->getPhoto($unit,$grid_unit);

        $this->toJson($data);
    }

    function actionChamberGetphoto(){
        $this->setNoRender();

        $unit = mb_strtolower($this->registry->virtual_modul_index);
        $grid_unit = "photo_$unit";

        $data = $this->model->getPhoto($unit,$grid_unit);

        $this->toJson($data);
    }

    function actionWardrobeGetphoto(){
        $this->setNoRender();

        $unit = mb_strtolower($this->registry->virtual_modul_index);
        $grid_unit = "photo_$unit";

        $data = $this->model->getPhoto($unit,$grid_unit);

        $this->toJson($data);
    }

    private function _editcell(){
        $result = true;

        $id = $this->registry->request->postParam('id') ;
        $oper = $this->registry->request->postParam('oper') ;
        $sort = $this->registry->request->postParam('sort') ;
        $text = $this->registry->request->postParam('text') ;
        $title = $this->registry->request->postParam('title') ;

        $data = array(
            "title" => $title,
            "text" => $text,
            "sort" => $sort,
        );

        $entity = 'photo';
        $model_name = ucfirst($entity) . "Model";
        $model = new $model_name('photo_id', $id);
        $data_exists = $model->getData();


        if(isset($data_exists[0])){
            $data = array_merge($data_exists[0],$data );
        }

        $data = array(0 => $data);

        $model->setData($data);

        $model->Flush();

        return $result;
    }

    private function editCellAll(){
        $this->setNoRender();

        $status = '';

        if( ($res = $this->_editcell()) === true){
            $status = 'ok';
        }

        $this->json($data = array('responsestatus' => $status));
    }

    function actionDiningEditcell(){
        $this->editCellAll();
    }

    function actionChamberEditcell(){
        $this->editCellAll();
    }

    function actionWardrobeEditcell(){
        $this->editCellAll();
    }

    function actionDiningДобавитьфото (){

        if($this->registry->request->get(3) == 'new'){
            $result = $this->insertPhoto($this->virtual_modul_index);

            if((bool)$result === false){
                fb($this->virtual_modul_index . ": Добавитьфото error");
                //$this->html =  $this->view->render('photo.edit.tpl');
            } else {
                header('Location:' . PUBLIC_URL . '/'.$this->virtual_modul_index);
            }
        }

        return false;
    }

    function actionChamberДобавитьфото (){

        if($this->registry->request->get(3) == 'new'){
            $result = $this->insertPhoto($this->virtual_modul_index);

            if((bool)$result === false){
                fb($this->virtual_modul_index . ": Добавитьфото error");
                //$this->html =  $this->view->render('photo.edit.tpl');
            } else {
                header('Location:' . PUBLIC_URL . '/'.$this->virtual_modul_index);
            }
        }

        return false;
    }

    function actionWardrobeДобавитьфото (){

        if($this->registry->request->get(3) == 'new'){
            $result = $this->insertPhoto($this->virtual_modul_index);

            if((bool)$result === false){
                fb($this->virtual_modul_index . ": Добавитьфото error");
                //$this->html =  $this->view->render('photo.edit.tpl');
            } else {
                header('Location:' . PUBLIC_URL . '/'.$this->virtual_modul_index);
            }
        }

        return false;
    }

    private function insertPhoto($unit = null){
        # Залить фото
        $pk = false;

        $filename = $_FILES['photo']['name'];
        $unit = mb_strtolower($this->registry->virtual_modul_index);

        $rnd_val = md5(rand() . date("H:i:s"));
        $rnd_val = md5($rnd_val . $unit . rand());
        $rnd_val = substr($rnd_val,0,8);

        $link = $rnd_val . ".jpg";

        $local_path = "tmp/";
        $file_1 = $link; //$filename;
        $file_1_up = $file_1;
        $file_1 = PUBLIC_PATH . "/tmp/$file_1";;
        $file_2 = 'sm_'.$link;
        $file_2_up = $file_2;
        $file_2 = PUBLIC_PATH . "/tmp/$file_2";

        $this->model->imgCropAndResize($_FILES['photo']['tmp_name'],$file_1,900,600);
        $this->model->imgCropAndResize($_FILES['photo']['tmp_name'],$file_2,300,200);

        if($this->model->uploadImage($file_1_up, $unit)){
            $this->model->uploadImage($file_2_up, $unit);
        }

        @unlink($file_1);
        @unlink($file_2);

        # Записать в базу
        $rnd_val = md5(rand() . date("H:i:s"));
        $rnd_val = substr($rnd_val,0,8);

        $link = "{$this->registry->virtual_modul_id}_{$rnd_val}" . substr($file_1_up,0,-5);

        $data = array('vmodul_id' =>  $this->registry->virtual_modul_id,
                      'date_added' => date("Y-m-d H:i:s"),
                      'title' => '',
                      'text' => '',
                      'link' => $file_1_up,
                      'sort' => 100,
        );

        $PhotoModel = new PhotoModel();
        $pk = $PhotoModel->Set($data);

        return $pk;
    }

    /*
     * [универсальный] метод загрузки файлов с сервера на ftp
     */
    private function imageToFtp(array $photo_arr, $unit){



        $result = true;

        foreach($photo_arr as $k => $v){

            $pk = false;
            $local_path = $v;

            $link = md5(rand() . date("H:i:s"));
            $link = md5($link . $unit . rand());
            $link = substr($link,0,8);
            $link = $link . ".jpg";





            $this->model->imgCropAndResize($local_path,PUBLIC_PATH . "/tmp/$link",900,600);
            $this->model->imgCropAndResize($local_path,PUBLIC_PATH . "/tmp/sm_" . $link,300,200);

            $this->model->openFtpConnection();

            $this->model->putRemoteFile($link, PUBLIC_PATH . "/tmp", null, $unit, true);
            $this->model->putRemoteFile("sm_$link", PUBLIC_PATH . "/tmp", null, $unit, true);


            @unlink($local_path);
            @unlink(PUBLIC_PATH . "/tmp/$link");
            @unlink(PUBLIC_PATH . "/tmp/sm_" . $link);

            $this->model->closeFtpConnection();


            # Записать в базу
            $data = array('vmodul_id' =>  $this->registry->virtual_modul_id,
                          'date_added' => date("Y-m-d H:i:s"),
                          'title' => '',
                          'text' => '',
                          'link' => $link,
                          'sort' => 100,
            );

            $PhotoModel = new PhotoModel();
            $pk = $PhotoModel->Set($data);

        }


        return $result;

    }

    function actionDiningMultisave(){

        $this->setNoRender();

        $mess = '';
        $status = 'ok';
        $multisave_arr = array();
        $unit = mb_strtolower($this->registry->virtual_modul_index);

        #
        if(isset($_SESSION['multisave_arr'])){
            $multisave_arr = $_SESSION['multisave_arr'];
            unset($_SESSION['multisave_arr']);
        }

        $image_to_ftp = $this->imageToFtp($multisave_arr, $unit);

        #
        $data = array(
            'status' => $status,
            'mess' => $mess,
        );

        $this->jsonSend($data);
    }

    function actionChamberMultisave(){

        $this->setNoRender();

        $mess = '';
        $status = 'ok';
        $multisave_arr = array();
        $unit = mb_strtolower($this->registry->virtual_modul_index);

        #
        if(isset($_SESSION['multisave_arr'])){
            $multisave_arr = $_SESSION['multisave_arr'];
            unset($_SESSION['multisave_arr']);
        }

        $image_to_ftp = $this->imageToFtp($multisave_arr, $unit);

        #
        $data = array(
            'status' => $status,
            'mess' => $mess,
        );

        $this->jsonSend($data);
    }

    function actionWardrobeMultisave(){

        $this->setNoRender();

        $mess = '';
        $status = 'ok';
        $multisave_arr = array();
        $unit = mb_strtolower($this->registry->virtual_modul_index);

        #
        if(isset($_SESSION['multisave_arr'])){
            $multisave_arr = $_SESSION['multisave_arr'];
            unset($_SESSION['multisave_arr']);
        }

        $image_to_ftp = $this->imageToFtp($multisave_arr, $unit);

        #
        $data = array(
            'status' => $status,
            'mess' => $mess,
        );

        $this->jsonSend($data);
    }














}